package com.liuxin.zhiyuan.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuxin.common.config.JwtProperties;
import com.liuxin.common.exception.BadRequestException;
import com.liuxin.common.exception.ForbiddenException;
import com.liuxin.common.utils.JwtTool;
import com.liuxin.zhiyuan.user.domain.dto.LoginFormDTO;
import com.liuxin.zhiyuan.user.domain.po.LxzyUser;
import com.liuxin.zhiyuan.user.domain.vo.UserInfoVO;
import com.liuxin.zhiyuan.user.domain.vo.UserLoginVO;
import com.liuxin.zhiyuan.user.mapper.LxzyUserMapper;
import com.liuxin.zhiyuan.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Assert;

import java.util.Date;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<LxzyUserMapper, LxzyUser> implements UserService {

    private final PasswordEncoder passwordEncoder;
    private final JwtTool jwtTool;
    private final JwtProperties jwtProperties;

    @Override
    public UserLoginVO login(LoginFormDTO loginDTO) {
        String phone = loginDTO.getPhone();
        String password = loginDTO.getPassword();
        LxzyUser user = lambdaQuery().eq(LxzyUser::getPhone, phone).one();
        Assert.notNull(user, "手机号或密码错误！");
        // 3.校验是否禁用
        if (user.getEnable() != null && user.getEnable() == 0) {
            throw new ForbiddenException("用户被禁用");
        }
        // 4.校验密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new BadRequestException("手机号或密码错误");
        }
        // 5.生成TOKEN
        String token = jwtTool.createToken(user.getId(), jwtProperties.getTokenTTL());
        // 6.封装VO返回
        UserLoginVO vo = new UserLoginVO();
        vo.setToken(token);
        // 7.更新最后登录时间
        user.setLastLoginTime(new Date());
        baseMapper.updateById(user);
        return vo;
    }

    @Override
    public UserInfoVO queryUserInfo(Long userId) {
        UserInfoVO userInfoVO = baseMapper.queryUserInfo(userId);
        return userInfoVO;
    }

     @Override
    public void updateLastLoginTime(Long userId) {
        LxzyUser user = new LxzyUser();
        user.setId(userId);
        user.setLastLoginTime(new Date());
        baseMapper.updateById(user);
    }

}
